﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using Table= FCNS.Data.Table;
using DoubleH.Utility;
using DoubleH;
using DoubleH.Utility.IO;
using DoubleH.Utility.Configuration;
using FCNS.Data;
using System.Collections.ObjectModel;

namespace ProductS
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        Table.ProductS order = null;

        public MainWindow()
        {
            InitializeComponent();

            InitVar();
        }

        public void Init(Table.ProductS obj)
        {
            order = obj ?? new Table.ProductS();
            InitOrder();
            InitEvent();
            //web.Loaded += new RoutedEventHandler(web_Loaded);
        }

        private void InitVar()
        {
            uCGroupS1.Init(Table.GroupS.EnumFlag.商品分类);
            uCUniqueSBrand.Init(Table.UniqueS.EnumFlag.品牌);
            uCUniqueSPlace.Init(Table.UniqueS.EnumFlag.产地);
            uCUniqueSUnit.Init(Table.UniqueS.EnumFlag.计量单位);
            uCUniqueSRack.Init(Table.UniqueS.EnumFlag.货架);
            uCUniqueSRow.Init(Table.UniqueS.EnumFlag.行);
        }

        private void InitOrder()
        {
            uCUniqueSUnit.SelectedObjectId = order.UnitId;
            uCGroupS1.SelectedObjectId = order.GroupSId;
            uCUniqueSBrand.SelectedObjectId = order.BrandId;
            uCUniqueSPlace.SelectedObjectId = order.PlaceId;

            textBoxName.Text = order.Name;
            textBoxCode.Text = order.Code;
            textBoxBarcode.Text = order.Barcode;
            textBoxStandard.Text = order.Standard;
            textBoxModel.Text = order.Model;
            textBoxNote.Text = order.Note;
            textBoxPinYinLong.Text = order.PinYinL;
            textBoxPinYinShort.Text = order.PinYinS;

            bool isUsed = order.IsUsed();
            InitOrderFlag(isUsed);
            InitWuLiao(isUsed);
            //ConfigControlAfterChecked();

            checkBoxScore.IsChecked = order.IsScore;
            checkBoxDiscount.IsChecked = order.IsDiscount;
            if (order.IsScore)
            {
                if (order.Score == 0)
                    radioButtonScoreDefault.IsChecked = true;
                else
                {
                    radioButtonScoreCustom.IsChecked = true;
                    integerUpDownScoreCustom.Value = (int)order.Score;
                }
            }
            //相关属性
            integerUpDownBaoXiu.Value = (int)order.BaoXiu;
            uCUniqueSRack.SelectedObjectId = order.RackId;
            uCUniqueSRow.SelectedObjectId = order.RowId;
            doubleUpDownGrossWeight.Value = order.GrossWeight;
            doubleUpDownNetWeight.Value = order.NetWeight;
            doubleUpDownVolume.Value = order.Volume;
            //会员
            checkBoxDiscount.IsChecked = order.IsDiscount;
            //价格
            doubleUpDownPurchasePrice.Value = order.PurchasePrice;
            doubleUpDownWholesalePrice1.Value = order.WholesalePrice1;
            doubleUpDownWholesalePrice2.Value = order.WholesalePrice2;
            doubleUpDownWholesalePrice3.Value = order.WholesalePrice3;
            doubleUpDownWholesalePrice4.Value = order.WholesalePrice4;
            doubleUpDownWholesalePrice5.Value = order.WholesalePrice5;
            doubleUpDownPosPrice.Value = order.PosPrice;
            doubleUpDownVip.Value = order.VipPrice;
            doubleUpDownWholesaleMaximum.Value = order.WholesalePriceMaximum;
            doubleUpDownWholesalePriceMinimum.Value = order.WholesalePriceMinimum;
            //仓库
            SqlFunction sqlf = new SqlFunction();
            dataGridStoreS.ItemsSource = sqlf.GetStoreSProperty(order.Id);
            //图片
            uCImage1.ImageFile = order._ImageFile;
        }

        private void InitEvent()
        {
            //checkBoxIsPurchase.Click += (ss, ee) => ConfigControlAfterChecked();
            //checkBoxIsSales.Click += (ss, ee) => ConfigControlAfterChecked();
            //checkBoxCombo.Click += (ss, ee) => ConfigControlAfterChecked();
            //checkBoxNoKuCun.Click += (ss, ee) => ConfigControlAfterChecked();
            buttonSave.Click += (ss, ee) => Save();
            buttonBarcode.Click += (ss, ee) => SearchBarcode();
        }

        #region 网页查询条码库功能
        private void SearchBarcode()
        {
            //if (!string.IsNullOrEmpty(textBoxName.Text) || string.IsNullOrEmpty(textBoxBarcode.Text))
            //    return;


            //web.Navigate("http://www.gds.org.cn");
        }

        void web_Loaded(object sender, RoutedEventArgs e)
        {
            //if (web.Document == null)
            //    return;

            //MessageBox.Show(web.Source.AbsoluteUri + "  " + web.Source.Host);
            //if (web.Source.Host.Contains("gds.org"))
            //{

            //    mshtml.IHTMLDocument2 doc2 = (mshtml.IHTMLDocument2)web.Document;
            //    mshtml.IHTMLElement keyword = (mshtml.IHTMLElement)doc2.all.item("keyword", 0);
            //    keyword.setAttribute("placeholder", textBoxBarcode.Text);
            //    MessageBox.Show(keyword.getAttribute("placeholder"));
            //    mshtml.IHTMLElement gdsBtn = (mshtml.IHTMLElement)doc2.all.item("gdsBtn", 0);
            //    gdsBtn.click();
            //    doc2.close();
            //}
            //else
            //{
            //    MessageBox.Show("vvv");
            //    MessageBox.Show(web.Document.ToString());
            //}
        }
        #endregion

        //private void ConfigControlAfterChecked()
        //{
        //    if (checkBoxNoKuCun.IsChecked.Value)
        //        checkBoxIsPurchase.IsChecked = false;

        //    bool p = checkBoxIsPurchase.IsChecked.Value;
        //    tabItemStore.Visibility = p ? Visibility.Visible : Visibility.Collapsed;

        //    bool s = checkBoxIsSales.IsChecked.Value;
        //    tabItemSale.Visibility = s ? Visibility.Visible : Visibility.Collapsed;
        //    tabItemDiscount.Visibility = s ? Visibility.Visible : Visibility.Collapsed;

        //    if (!p && !s)
        //        tabControl1.Visibility = Visibility.Hidden;
        //    else
        //    {
        //        tabControl1.Visibility = Visibility.Visible;
        //        tabControl1.SelectedIndex = p ? 0 : 2;
        //    }

        //    tabItemCombo.Visibility = checkBoxCombo.IsChecked.Value ? Visibility.Visible : Visibility.Collapsed;
        //}

        private void InitOrderFlag(bool isUsed)
        {
            if (isUsed)
            {
                switch (order.Flag)
                {
                    case Table.ProductS.EnumFlag.免库存:
                        checkBoxIsPurchase.IsEnabled = false;
                        checkBoxIsSales.IsEnabled = false;
                        checkBoxCombo.IsEnabled = false;
                        checkBoxNoKuCun.IsEnabled = false;
                        break;

                    case Table.ProductS.EnumFlag.可采购:
                    case Table.ProductS.EnumFlag.可销售:
                    case Table.ProductS.EnumFlag.可销售和可采购:
                        checkBoxNoKuCun.IsEnabled = false;
                        checkBoxCombo.IsEnabled = false;
                        break;
                }
            }

            switch (order.Flag)
            {
                case Table.ProductS.EnumFlag.免库存:
                    checkBoxNoKuCun.IsChecked = true;
                    checkBoxIsSales.IsChecked = true;
                    break;

                case Table.ProductS.EnumFlag.可采购: checkBoxIsPurchase.IsChecked = true; break;
                case Table.ProductS.EnumFlag.可销售: checkBoxIsSales.IsChecked = true; break;
                case Table.ProductS.EnumFlag.可销售和可采购:
                    checkBoxIsPurchase.IsChecked = true;
                    checkBoxIsSales.IsChecked = true;
                    break;
            }

            checkBoxIsPurchase.IsEnabled = Table.SysConfig.SysConfigParams.UsePurchaseOrderS;
            checkBoxIsSales.IsEnabled = Table.SysConfig.SysConfigParams.UseSalesOrderS;
            checkBoxVisible.IsChecked = order.Enable == Table.ProductS.EnumEnable.停用 ? true : false;
        }

        private void InitWuLiao(bool isUsed)
        {
            if (order.IsWuLiao)
            {
                checkBoxCombo.IsChecked = true;
                if (isUsed)
                {
                    checkBoxNoKuCun.IsEnabled = false;
                    checkBoxCombo.IsEnabled = false;
                    productSListInfoWuLiao.ShowBodyContexMenu = false;
                }
                else
                    productSListInfoWuLiao.ShowBodyContexMenu = true;
            }

            //productSListInfoWuLiao.AbsQuantity = true;
            productSListInfoWuLiao.MustHasStoreS = false;
            productSListInfoWuLiao.Init(DoubleHConfig.UserConfig.GetUserUIparams(DataTableText.物料清单商品编辑));
            productSListInfoWuLiao.CanUserAddRows = false;
            productSListInfoWuLiao.ItemsSource = order._WuLiaoQingDan;
            productSListInfoWuLiao.ShowBottom = false;
            productSListInfoWuLiao.CanNegativeSales = true;
            productSListInfoWuLiao.IsReadOnly = !checkBoxCombo.IsEnabled;//如果物料清单已经有出入库记录,就不能更改清单内容,也不可以修改数量.
            productSListInfoWuLiao.DataGrid.GetColumn("_TempPrice").Visibility =
                ((order.Flag != Table.ProductS.EnumFlag.可销售 &&
                order.Flag != Table.ProductS.EnumFlag.免库存) ? Visibility.Visible : Visibility.Collapsed);

            productSListInfoWuLiao.TempPriceEdited += (ee) => CheckPercent(ee);
        }

        private void CheckPercent(DataGridCellEditEndingEventArgs ee)
        {
            TextBox tb = ee.EditingElement as TextBox;
            if (tb == null)
                return;

            double d = Convert.ToDouble(tb.Text);
            if (d > 1)
                d = 1;
            else if (d < 0)
                d = 0;

            tb.Text = d.ToString();
        }

        private void Save()
        {
            if (order.BarcodeIsExists(textBoxBarcode.Text) && MessageWindow.Show("", "条形码已被其它商品使用，是否继续？", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;

            Table.ProductS.EnumFlag flag = Table.ProductS.EnumFlag.可销售和可采购;

            if (checkBoxCombo.IsChecked.Value)
                order.IsWuLiao = true;
            else
            {
                order.IsWuLiao = false;
                order._WuLiaoQingDan.Clear();
            }
            if (checkBoxNoKuCun.IsChecked.Value)
                flag = Table.ProductS.EnumFlag.免库存;
            else if (checkBoxIsPurchase.IsChecked == true && checkBoxIsSales.IsChecked == false)
                flag = Table.ProductS.EnumFlag.可采购;
            else if (checkBoxIsPurchase.IsChecked == false && checkBoxIsSales.IsChecked == true)
                flag = Table.ProductS.EnumFlag.可销售;

            order.Flag = flag;

            order.Enable = checkBoxVisible.IsChecked.Value ? Table.ProductS.EnumEnable.停用 : Table.ProductS.EnumEnable.启用;
            order.IsScore = checkBoxScore.IsChecked.Value;
            order.IsDiscount = checkBoxDiscount.IsChecked.Value;

            order.BaoXiu = integerUpDownBaoXiu.Value.HasValue ? integerUpDownBaoXiu.Value.Value : 0;
            order.IsDiscount = checkBoxDiscount.IsChecked.Value;
            if (checkBoxScore.IsChecked.Value)
            {
                if (radioButtonScoreDefault.IsChecked.Value)
                    order.Score = 0;
                else
                    order.Score = integerUpDownScoreCustom.Value.Value;
            }

            order.Name = textBoxName.Text.Trim();
            order.Barcode = textBoxBarcode.Text;
            order.Standard = textBoxStandard.Text;
            order.Model = textBoxModel.Text;
            order.Note = textBoxNote.Text;
            order.Code = textBoxCode.Text;
            order.PinYinS = textBoxPinYinShort.Text;
            order.PinYinL = textBoxPinYinLong.Text;
            order.GroupSId = uCGroupS1.SelectedObjectId;
            order.UnitId = uCUniqueSUnit.SelectedObjectId;
            order.PlaceId = uCUniqueSPlace.SelectedObjectId;
            order.BrandId = uCUniqueSBrand.SelectedObjectId;
            order.Volume = doubleUpDownVolume.Value.Value;
            order.GrossWeight = doubleUpDownGrossWeight.Value.Value;
            order.NetWeight = doubleUpDownNetWeight.Value.Value;
            order.RackId = uCUniqueSRack.SelectedObjectId;
            order.RowId = uCUniqueSRow.SelectedObjectId;
            order.PurchasePrice = doubleUpDownPurchasePrice.Value.Value;
            order.WholesalePrice1 = doubleUpDownWholesalePrice1.Value.Value;
            order.WholesalePrice2 = doubleUpDownWholesalePrice2.Value.Value;
            order.WholesalePrice3 = doubleUpDownWholesalePrice3.Value.Value;
            order.WholesalePrice4 = doubleUpDownWholesalePrice4.Value.Value;
            order.WholesalePrice5 = doubleUpDownWholesalePrice5.Value.Value;
            order.PosPrice = doubleUpDownPosPrice.Value.Value;
            order.VipPrice = doubleUpDownVip.Value.Value;
            order.WholesalePriceMinimum = doubleUpDownWholesalePriceMinimum.Value.Value;
            order.WholesalePriceMaximum = doubleUpDownWholesaleMaximum.Value.Value;

            // order._WuLiaoQingDan = (ObservableCollection<Table.ProductS>)productSListInfoWuLiao.ItemsSource;

            order.UploadFile = uCImage1.UploadFileName;

            Table.DataTableS.EnumDatabaseStatus result = Table.DataTableS.EnumDatabaseStatus.操作成功;
            if (order.Id == -1)
                result = order.Insert();
            else
            {
                result = order.Update();
                foreach (StoreSProperty ssp in dataGridStoreS.ItemsSource)
                    Table.ProductSInStoreS.SetQuantityMaxAndMin(order.Id, ssp.Id, ssp.QuantityMax, ssp.QuantityMin);
            }

            if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
            {
                uCImage1.UpdateImage(Table.ProductS.tableName);
                this.Close();
            }
            else
                MessageWindow.Show(result.ToString());
        }

        private void checkBoxDiscount_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {

        }
    }
}